#include <webx/route.h>

class GetNoteList : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(GetNoteList, "/compile/${filename}")

int GetNoteList::process()
{
	param_string(id);
	param_string(level);
	param_string(title);
	param_string(folder);

	string dbid;
	string sqlcmd;
	const string& user = checkLogin();

	if (webx::IsAlnumString(id))
	{
		dbid = token->getDataId();
		stdx::format(sqlcmd, "SELECT ID,ICON,LEVEL,TITLE,FOLDER,STATETIME FROM T_XG_CODE WHERE USER='%s' AND ID='%s' AND LENGTH(TITLE)>0", user.c_str(), id.c_str());
	}
	else if (folder.empty())
	{
		dbid = token->getDataId();
		stdx::format(sqlcmd, "SELECT ID,ICON,LEVEL,TITLE,FOLDER,STATETIME FROM T_XG_CODE WHERE USER='%s' AND LENGTH(TITLE)>0 ORDER BY FOLDER ASC,POSITION ASC", user.c_str());
	}
	else if (webx::IsFileName(title))
	{
		stdx::format(sqlcmd, "SELECT ID,ICON,LEVEL,TITLE,FOLDER,STATETIME FROM T_XG_CODE WHERE FOLDER='WEBPAGE' AND TITLE='%s'", title.c_str());
	}
	else
	{
		webx::CheckFileName(folder);

		if (folder == "WEBPAGE")
		{
			stdx::format(sqlcmd, "SELECT ID,ICON,LEVEL,TITLE,FOLDER,STATETIME FROM T_XG_CODE WHERE FOLDER='WEBPAGE' AND LENGTH(TITLE)>0 ORDER BY POSITION ASC");
		}
		else
		{
			dbid = token->getDataId();

			if (IsNumberString(level.c_str()))
			{
				stdx::format(sqlcmd, "SELECT ID,ICON,LEVEL,TITLE,FOLDER,STATETIME FROM T_XG_CODE WHERE USER='%s' AND FOLDER='%s' AND LENGTH(TITLE)>0 AND LEVEL=%s ORDER BY POSITION ASC", user.c_str(), folder.c_str(), level.c_str());
			}
			else
			{
				stdx::format(sqlcmd, "SELECT ID,ICON,LEVEL,TITLE,FOLDER,STATETIME FROM T_XG_CODE WHERE USER='%s' AND FOLDER='%s' AND LENGTH(TITLE)>0 ORDER BY POSITION ASC", user.c_str(), folder.c_str());
			}
		}
	}
	
	json["code"] = webx::PackJson(webx::GetDBConnect(dbid)->query(sqlcmd), "list", json);
	json["dbid"] = dbid;
	out << json;

	return XG_OK;
}